package cn.tedu.executorservice;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class ForkjoinPoolDemo {
    public static void main(String[] args) {
        long beginTime = System.currentTimeMillis();

//        long sum = 0L;
//        for (long i = 1; i <= 100000000000L; ++i) {
//            sum += i;
//        }
//        System.out.println(sum);

        try {
            ForkJoinPool pool = new ForkJoinPool();
            Future<Long> f = pool.submit(new Sum(1, 100000000000L));
            pool.shutdown();
            System.out.println(f.get());
        } catch (ExecutionException executionException) {
            executionException.printStackTrace();
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("执行时间:");
        System.out.println(endTime - beginTime);
    }
}

class Sum extends RecursiveTask<Long> {
    private long start;
    private long end;

    public Sum(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start <= 10000L) {
            // 如果数字不多, 直接计算
            long sum = 0;
            for (long i = start; i <= end; ++i) {
                sum += i;
            }
            return sum;
        } else {
            // 如果start - end数字依然比较多, 那么就继续拆分
            long mid = (start + end) / 2;
            Sum left = new Sum (start, mid);
            Sum right = new Sum(mid + 1, end);
            // 拆分成了2个子任务
            left.fork();
            right.fork();
            // 需要将2个子任务的结果进行汇总才是这个范围内的最终结果
            return left.join() + right.join();
        }
    }
}
